"""
API 路由定义
"""

import os
from datetime import datetime
from flask import request, jsonify, Blueprint
from ..services.binance_client import BinanceDataClient, SUPPORTED_INTERVALS
from ..services.indicators_service import IndicatorsService
from ..services.chart_service import ChartService
from ..services.ai_strategy_service import AIStrategyService
from ..services.backtesting_service import BacktestingService

# 创建蓝图
api_bp = Blueprint('api', __name__, url_prefix='/api')

# 延迟初始化服务实例（避免启动时的网络连接）
_binance_client = None
_indicators_service = None


def _get_binance_client() -> BinanceDataClient:
    """获取 Binance 客户端实例（延迟初始化）"""
    global _binance_client
    if _binance_client is None:
        _binance_client = BinanceDataClient()
    return _binance_client


def _get_indicators_service() -> IndicatorsService:
    """获取指标服务实例（延迟初始化）"""
    global _indicators_service
    if _indicators_service is None:
        _indicators_service = IndicatorsService()
    return _indicators_service


@api_bp.route('/klines', methods=['GET'])
def get_klines() -> tuple:
    """
    获取 K 线数据

    查询参数：
    - symbol: 交易对符号 (必填，例如 'BTCUSDT')
    - interval: 时间周期 (必填，支持: '5m', '15m', '1h', '4h', '1d')
    - start_time: 开始时间 (可选，格式: 'YYYY-MM-DD HH:MM')
    - end_time: 结束时间 (可选，格式: 'YYYY-MM-DD HH:MM')
    - limit: 返回条数 (可选，默认 500，最大 1500)
    """
    try:
        # 获取查询参数
        symbol = request.args.get('symbol')
        interval = request.args.get('interval')
        start_time_str = request.args.get('start_time')
        end_time_str = request.args.get('end_time')
        limit = request.args.get('limit', 500, type=int)

        # 验证必填参数
        if not symbol:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": "缺少必填参数: symbol"
            }), 400

        if not interval:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": "缺少必填参数: interval"
            }), 400

        # 验证时间周期
        if interval not in SUPPORTED_INTERVALS.__args__:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": f"不支持的时间周期，支持: {', '.join(SUPPORTED_INTERVALS.__args__)}"
            }), 400

        # 验证交易对
        binance_client = _get_binance_client()
        if not binance_client.validate_symbol(symbol):
            return jsonify({
                "code": 400,
                "data": {},
                "msg": f"交易对 '{symbol}' 不存在"
            }), 400

        # 解析时间参数
        start_time = None
        end_time = None

        if start_time_str:
            try:
                start_time = datetime.strptime(start_time_str, '%Y-%m-%d %H:%M')
            except ValueError:
                return jsonify({
                    "code": 400,
                    "data": {},
                    "msg": "start_time 格式错误，请使用 'YYYY-MM-DD HH:MM'"
                }), 400

        if end_time_str:
            try:
                end_time = datetime.strptime(end_time_str, '%Y-%m-%d %H:%M')
            except ValueError:
                return jsonify({
                    "code": 400,
                    "data": {},
                    "msg": "end_time 格式错误，请使用 'YYYY-MM-DD HH:MM'"
                }), 400

        # 验证时间范围
        if start_time and end_time and start_time >= end_time:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": "开始时间必须早于结束时间"
            }), 400

        # 获取数据
        klines = binance_client.get_klines(
            symbol=symbol,
            interval=interval,  # type: ignore
            start_time=start_time,
            end_time=end_time,
            limit=limit
        )

        return jsonify({
            "code": 200,
            "data": {
                "symbol": symbol,
                "interval": interval,
                "count": len(klines),
                "klines": klines
            },
            "msg": "success"
        }), 200

    except Exception as e:
        return jsonify({
            "code": 500,
            "data": {},
            "msg": f"获取数据失败: {str(e)}"
        }), 500


@api_bp.route('/indicators', methods=['GET'])
def get_indicators() -> tuple:
    """
    获取技术指标数据

    查询参数：
    - symbol: 交易对符号 (必填，例如 'ETHUSDT')
    - timeframe: 时间框架 (可选，支持: '3m', '4h', 'both', 默认 'both')
    """
    try:
        # 获取查询参数
        symbol = request.args.get('symbol')
        timeframe = request.args.get('timeframe', 'both')

        # 验证必填参数
        if not symbol:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": "缺少必填参数: symbol"
            }), 400

        # 验证交易对
        binance_client = _get_binance_client()
        if not binance_client.validate_symbol(symbol):
            return jsonify({
                "code": 400,
                "data": {},
                "msg": f"交易对 '{symbol}' 不存在"
            }), 400

        # 验证时间框架
        if timeframe not in ['3m', '4h', 'both']:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": "不支持的时间框架，支持: 3m, 4h, both"
            }), 400

        # 获取指标数据
        indicators_service = _get_indicators_service()
        if timeframe == 'both':
            indicators = indicators_service.get_3m_and_4h_indicators(symbol)
        elif timeframe == '3m':
            indicators = indicators_service.get_3m_indicators(symbol)
        else:  # 4h
            indicators = indicators_service.get_4h_indicators(symbol)

        return jsonify({
            "code": 200,
            "data": indicators,
            "msg": "success"
        }), 200

    except ValueError as e:
        return jsonify({
            "code": 400,
            "data": {},
            "msg": str(e)
        }), 400
    except Exception as e:
        return jsonify({
            "code": 500,
            "data": {},
            "msg": f"获取指标数据失败: {str(e)}"
        }), 500


# 延迟初始化图表服务实例
_chart_service = None


def _get_chart_service() -> ChartService:
    """获取图表服务实例（延迟初始化）"""
    global _chart_service
    if _chart_service is None:
        _chart_service = ChartService()
    return _chart_service


@api_bp.route('/chart/klines', methods=['GET'])
def generate_klines_chart() -> tuple:
    """
    生成K线图

    查询参数：
    - symbol: 交易对符号 (必填，例如 'BTCUSDT')
    - interval: 时间周期 (必填，支持: '5m', '15m', '1h', '4h', '1d')
    - chart_type: 图表类型 (可选，'candlestick' 或 'line', 默认 'candlestick')
    - show_volume: 是否显示成交量 (可选，'true' 或 'false', 默认 'true')
    - start_time: 开始时间 (可选，格式: 'YYYY-MM-DD HH:MM')
    - end_time: 结束时间 (可选，格式: 'YYYY-MM-DD HH:MM')
    - limit: 返回条数 (可选，默认 100，最大 300)
    """
    try:
        # 获取查询参数
        symbol = request.args.get('symbol')
        interval = request.args.get('interval')
        chart_type = request.args.get('chart_type', 'candlestick')
        show_volume = request.args.get('show_volume', 'true').lower() == 'true'
        start_time_str = request.args.get('start_time')
        end_time_str = request.args.get('end_time')
        limit = request.args.get('limit', 100, type=int)

        # 验证必填参数
        if not symbol:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": "缺少必填参数: symbol"
            }), 400

        if not interval:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": "缺少必填参数: interval"
            }), 400

        # 验证时间周期
        if interval not in SUPPORTED_INTERVALS.__args__:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": f"不支持的时间周期，支持: {', '.join(SUPPORTED_INTERVALS.__args__)}"
            }), 400

        # 验证图表类型
        if chart_type not in ['candlestick', 'line']:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": "不支持的图表类型，支持: candlestick, line"
            }), 400

        # 验证交易对
        binance_client = _get_binance_client()
        if not binance_client.validate_symbol(symbol):
            return jsonify({
                "code": 400,
                "data": {},
                "msg": f"交易对 '{symbol}' 不存在"
            }), 400

        # 解析时间参数
        start_time = None
        end_time = None

        if start_time_str:
            try:
                start_time = datetime.strptime(start_time_str, '%Y-%m-%d %H:%M')
            except ValueError:
                return jsonify({
                    "code": 400,
                    "data": {},
                    "msg": "start_time 格式错误，请使用 'YYYY-MM-DD HH:MM'"
                }), 400

        if end_time_str:
            try:
                end_time = datetime.strptime(end_time_str, '%Y-%m-%d %H:%M')
            except ValueError:
                return jsonify({
                    "code": 400,
                    "data": {},
                    "msg": "end_time 格式错误，请使用 'YYYY-MM-DD HH:MM'"
                }), 400

        # 验证时间范围
        if start_time and end_time and start_time >= end_time:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": "开始时间必须早于结束时间"
            }), 400

        # 获取K线数据
        klines = binance_client.get_klines(
            symbol=symbol,
            interval=interval,  # type: ignore
            start_time=start_time,
            end_time=end_time,
            limit=limit
        )

        if not klines:
            return jsonify({
                "code": 404,
                "data": {},
                "msg": "未获取到K线数据"
            }), 404

        # 生成K线图
        chart_service = _get_chart_service()
        chart_path = chart_service.generate_candlestick_chart(
            symbol=symbol,
            klines_data=klines,
            chart_type=chart_type,
            show_volume=show_volume
        )

        # 返回图片路径
        from ..config import config
        charts_dir = config.get_charts_dir()
        relative_path = os.path.relpath(chart_path, charts_dir)

        return jsonify({
            "code": 200,
            "data": {
                "symbol": symbol,
                "interval": interval,
                "chart_type": chart_type,
                "show_volume": show_volume,
                "image_url": f"/static/charts/{relative_path}",
                "image_path": chart_path,
                "data_count": len(klines)
            },
            "msg": "K线图生成成功"
        }), 200

    except ValueError as e:
        return jsonify({
            "code": 400,
            "data": {},
            "msg": str(e)
        }), 400
    except Exception as e:
        return jsonify({
            "code": 500,
            "data": {},
            "msg": f"生成K线图失败: {str(e)}"
        }), 500


# 延迟初始化AI策略服务实例
_ai_strategy_service = None


def _get_ai_strategy_service() -> AIStrategyService:
    """获取AI策略服务实例（延迟初始化）"""
    global _ai_strategy_service
    if _ai_strategy_service is None:
        _ai_strategy_service = AIStrategyService()
    return _ai_strategy_service


@api_bp.route('/strategy/analyze', methods=['GET'])
def analyze_trading_strategy() -> tuple:
    """
    使用大模型分析K线图并生成买卖策略

    查询参数：
    - symbol: 交易对符号 (必填，例如 'BTCUSDT')
    - interval: 时间周期 (必填，支持: '5m', '15m', '1h', '4h', '1d')
    - limit: K线数量 (可选，默认30，最大300)
    - chart_type: 图表类型 (可选，'candlestick' 或 'line', 默认 'candlestick')
    """
    try:
        # 获取查询参数
        symbol = request.args.get('symbol')
        interval = request.args.get('interval')
        limit = request.args.get('limit', 30, type=int)
        chart_type = request.args.get('chart_type', 'candlestick')

        # 验证必填参数
        if not symbol:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": "缺少必填参数: symbol"
            }), 400

        if not interval:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": "缺少必填参数: interval"
            }), 400

        # 验证时间周期
        if interval not in SUPPORTED_INTERVALS.__args__:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": f"不支持的时间周期，支持: {', '.join(SUPPORTED_INTERVALS.__args__)}"
            }), 400

        # 验证图表类型
        if chart_type not in ['candlestick', 'line']:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": "不支持的图表类型，支持: candlestick, line"
            }), 400

        # 验证限制数量
        if limit > 300:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": "限制数量不能超过300"
            }), 400

        # 验证交易对
        binance_client = _get_binance_client()
        if not binance_client.validate_symbol(symbol):
            return jsonify({
                "code": 400,
                "data": {},
                "msg": f"交易对 '{symbol}' 不存在"
            }), 400

        # 调用AI策略分析
        ai_strategy_service = _get_ai_strategy_service()
        result = ai_strategy_service.analyze_klines_with_ai(
            symbol=symbol,
            interval=interval,  # type: ignore
            limit=limit,
            chart_type=chart_type
        )

        return jsonify(result), result['code']

    except ValueError as e:
        return jsonify({
            "code": 400,
            "data": {},
            "msg": str(e)
        }), 400
    except Exception as e:
        return jsonify({
            "code": 500,
            "data": {},
            "msg": f"AI分析失败: {str(e)}"
        }), 500


# 延迟初始化回测服务实例
_backtesting_service = None


def _get_backtesting_service() -> BacktestingService:
    """获取回测服务实例（延迟初始化）"""
    global _backtesting_service
    if _backtesting_service is None:
        _backtesting_service = BacktestingService()
    return _backtesting_service


@api_bp.route('/strategy/backtesting', methods=['GET'])
def run_backtesting() -> tuple:
    """
    运行回测

    查询参数：
    - symbol: 交易对符号 (必填，例如 'BTCUSDT')
    - start_time: 开始时间 (必填，格式: 'YYYY-MM-DD')
    - end_time: 结束时间 (必填，格式: 'YYYY-MM-DD')
    - interval: 时间周期 (可选，支持: '5m', '15m', '1h', '4h', '1d', 默认 '15m')
    """
    try:
        # 获取查询参数
        symbol = request.args.get('symbol')
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        interval = request.args.get('interval', '15m')

        # 验证必填参数
        if not symbol:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": "缺少必填参数: symbol"
            }), 400

        if not start_time:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": "缺少必填参数: start_time"
            }), 400

        if not end_time:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": "缺少必填参数: end_time"
            }), 400

        # 验证时间周期
        if interval not in SUPPORTED_INTERVALS.__args__:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": f"不支持的时间周期，支持: {', '.join(SUPPORTED_INTERVALS.__args__)}"
            }), 400

        # 验证时间范围（v0.1.9: 支持分钟级别时间格式）
        try:
            # 尝试多种时间格式
            time_formats = [
                '%Y-%m-%d %H:%M:%S',  # 完整日期时间
                '%Y-%m-%d %H:%M',     # 简化日期时间
                '%Y-%m-%d'            # 仅日期（向后兼容）
            ]

            start_dt = None
            end_dt = None

            # 解析开始时间
            for fmt in time_formats:
                try:
                    start_dt = datetime.strptime(start_time, fmt)
                    break
                except ValueError:
                    continue

            if start_dt is None:
                raise ValueError(f"开始时间格式无效: {start_time}")

            # 解析结束时间
            for fmt in time_formats:
                try:
                    end_dt = datetime.strptime(end_time, fmt)
                    break
                except ValueError:
                    continue

            if end_dt is None:
                raise ValueError(f"结束时间格式无效: {end_time}")

            # 标准化到日期时间格式
            if start_dt.time() == datetime.min.time():
                start_dt = datetime.combine(start_dt.date(), datetime.min.time())
            if end_dt.time() == datetime.min.time():
                end_dt = datetime.combine(end_dt.date(), datetime.min.time())

            if start_dt > end_dt:
                return jsonify({
                    "code": 400,
                    "data": {},
                    "msg": "start_time 必须早于或等于 end_time"
                }), 400
        except ValueError as e:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": f"时间格式错误，支持格式：YYYY-MM-DD 或 YYYY-MM-DD HH:MM"
            }), 400

        # 验证交易对
        binance_client = _get_binance_client()
        if not binance_client.validate_symbol(symbol):
            return jsonify({
                "code": 400,
                "data": {},
                "msg": f"交易对 '{symbol}' 不存在"
            }), 400

        # 运行回测
        backtesting_service = _get_backtesting_service()
        result = backtesting_service.run_backtesting(
            symbol=symbol,
            start_time=start_time,
            end_time=end_time,
            interval=interval  # type: ignore
        )

        return jsonify(result), result['code']

    except ValueError as e:
        return jsonify({
            "code": 400,
            "data": {},
            "msg": str(e)
        }), 400
    except Exception as e:
        return jsonify({
            "code": 500,
            "data": {},
            "msg": f"回测失败: {str(e)}"
        }), 500


@api_bp.route('/strategy/backtesting/v8', methods=['GET'])
def run_backtesting_v8() -> tuple:
    """
    运行回测 - v0.0.8版本（滑动窗口递增算法）

    查询参数：
    - symbol: 交易对符号 (必填，例如 'BTCUSDT')
    - start_time: 开始时间 (必填，格式: 'YYYY-MM-DD')
    - end_time: 结束时间 (必填，格式: 'YYYY-MM-DD')
    - interval: 时间周期 (可选，支持: '5m', '15m', '1h', '4h', '1d', 默认 '15m')

    新算法特点：
    - 初始9小时数据作为基准
    - 逐根K线递进分析（滑动窗口）
    - 每根新K线都添加到历史中
    - AI建议使用 buy/sell/hold 英文格式
    """
    try:
        # 获取查询参数
        symbol = request.args.get('symbol')
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        interval = request.args.get('interval', '15m')

        # 验证必填参数
        if not symbol:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": "缺少必填参数: symbol"
            }), 400

        if not start_time:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": "缺少必填参数: start_time"
            }), 400

        if not end_time:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": "缺少必填参数: end_time"
            }), 400

        # 验证时间周期
        if interval not in SUPPORTED_INTERVALS.__args__:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": f"不支持的时间周期，支持: {', '.join(SUPPORTED_INTERVALS.__args__)}"
            }), 400

        # 验证时间范围（v0.1.9: 支持分钟级别时间格式）
        try:
            # 尝试多种时间格式
            time_formats = [
                '%Y-%m-%d %H:%M:%S',  # 完整日期时间
                '%Y-%m-%d %H:%M',     # 简化日期时间
                '%Y-%m-%d'            # 仅日期（向后兼容）
            ]

            start_dt = None
            end_dt = None

            # 解析开始时间
            for fmt in time_formats:
                try:
                    start_dt = datetime.strptime(start_time, fmt)
                    break
                except ValueError:
                    continue

            if start_dt is None:
                raise ValueError(f"开始时间格式无效: {start_time}")

            # 解析结束时间
            for fmt in time_formats:
                try:
                    end_dt = datetime.strptime(end_time, fmt)
                    break
                except ValueError:
                    continue

            if end_dt is None:
                raise ValueError(f"结束时间格式无效: {end_time}")

            # 标准化到日期时间格式
            if start_dt.time() == datetime.min.time():
                start_dt = datetime.combine(start_dt.date(), datetime.min.time())
            if end_dt.time() == datetime.min.time():
                end_dt = datetime.combine(end_dt.date(), datetime.min.time())

            if start_dt > end_dt:
                return jsonify({
                    "code": 400,
                    "data": {},
                    "msg": "start_time 必须早于或等于 end_time"
                }), 400
        except ValueError as e:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": f"时间格式错误，支持格式：YYYY-MM-DD 或 YYYY-MM-DD HH:MM"
            }), 400

        # 验证交易对
        binance_client = _get_binance_client()
        if not binance_client.validate_symbol(symbol):
            return jsonify({
                "code": 400,
                "data": {},
                "msg": f"交易对 '{symbol}' 不存在"
            }), 400

        # 运行回测
        backtesting_service = _get_backtesting_service()
        result = backtesting_service.run_backtesting(
            symbol=symbol,
            start_time=start_time,
            end_time=end_time,
            interval=interval  # type: ignore
        )

        return jsonify(result), result['code']

    except ValueError as e:
        return jsonify({
            "code": 400,
            "data": {},
            "msg": str(e)
        }), 400
    except Exception as e:
        return jsonify({
            "code": 500,
            "data": {},
            "msg": f"回测失败: {str(e)}"
        }), 500

# 延迟初始化v0.0.9回测服务实例
_backtesting_service_v9 = None


def _get_backtesting_service_v9() -> 'BacktestingServiceV9':
    """获取v0.0.9回测服务实例（延迟初始化）"""
    global _backtesting_service_v9
    if _backtesting_service_v9 is None:
        from ..services.backtesting_service_v9 import BacktestingServiceV9
        _backtesting_service_v9 = BacktestingServiceV9()
    return _backtesting_service_v9


@api_bp.route('/strategy/backtesting/v9', methods=['GET'])
def run_backtesting_v9() -> tuple:
    """
    运行回测 - v0.0.9版本（增量数据获取+缓存优化）

    查询参数：
    - symbol: 交易对符号 (必填，例如 'BTCUSDT')
    - start_time: 开始时间 (必填，格式: 'YYYY-MM-DD')
    - end_time: 结束时间 (必填，格式: 'YYYY-MM-DD')
    - interval: 时间周期 (可选，支持: '5m', '15m', '1h', '4h', '1d', 默认 '15m')

    版本特性：
    - v0.0.9: 使用CSV缓存，增量获取数据，图表命名优化
    - v0.1.1: 新增每次AI分析的详细结果和判定原因

    v0.0.9/v0.1.1特性：
    - 使用CSV缓存，增量获取数据
    - 图表命名：k_{symbol}_{start_time}_{end_time}_{interval}.png
    - 初始9小时数据，后续每次获取1根新K线
    - 支持同一天回测
    - v0.1.1新增：返回每次AI分析的详细结果和判定原因
    """
    try:
        # 获取查询参数
        symbol = request.args.get('symbol')
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        interval = request.args.get('interval', '15m')

        # 验证必填参数
        if not symbol:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": "缺少必填参数: symbol"
            }), 400

        if not start_time:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": "缺少必填参数: start_time"
            }), 400

        if not end_time:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": "缺少必填参数: end_time"
            }), 400

        # 验证时间周期
        if interval not in SUPPORTED_INTERVALS.__args__:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": f"不支持的时间周期，支持: {', '.join(SUPPORTED_INTERVALS.__args__)}"
            }), 400

        # 验证时间范围（v0.1.9: 支持分钟级别时间格式）
        try:
            # 尝试多种时间格式
            time_formats = [
                '%Y-%m-%d %H:%M:%S',  # 完整日期时间
                '%Y-%m-%d %H:%M',     # 简化日期时间
                '%Y-%m-%d'            # 仅日期（向后兼容）
            ]

            start_dt = None
            end_dt = None

            # 解析开始时间
            for fmt in time_formats:
                try:
                    start_dt = datetime.strptime(start_time, fmt)
                    break
                except ValueError:
                    continue

            if start_dt is None:
                raise ValueError(f"开始时间格式无效: {start_time}")

            # 解析结束时间
            for fmt in time_formats:
                try:
                    end_dt = datetime.strptime(end_time, fmt)
                    break
                except ValueError:
                    continue

            if end_dt is None:
                raise ValueError(f"结束时间格式无效: {end_time}")

            # 标准化到日期时间格式
            if start_dt.time() == datetime.min.time():
                start_dt = datetime.combine(start_dt.date(), datetime.min.time())
            if end_dt.time() == datetime.min.time():
                end_dt = datetime.combine(end_dt.date(), datetime.min.time())

            if start_dt > end_dt:
                return jsonify({
                    "code": 400,
                    "data": {},
                    "msg": "start_time 必须早于或等于 end_time"
                }), 400
        except ValueError as e:
            return jsonify({
                "code": 400,
                "data": {},
                "msg": f"时间格式错误，支持格式：YYYY-MM-DD 或 YYYY-MM-DD HH:MM"
            }), 400

        # 验证交易对
        binance_client = _get_binance_client()
        if not binance_client.validate_symbol(symbol):
            return jsonify({
                "code": 400,
                "data": {},
                "msg": f"交易对 '{symbol}' 不存在"
            }), 400

        # 运行v0.0.9回测
        # DEBUG: 添加调试日志，检查interval参数
        print(f"[DEBUG] run_backtesting_v9: interval={interval}, symbol={symbol}")
        backtesting_service = _get_backtesting_service_v9()
        result = backtesting_service.run_backtesting(
            symbol=symbol,
            start_time=start_time,
            end_time=end_time,
            interval=interval  # type: ignore
        )

        return jsonify(result), result['code']

    except ValueError as e:
        return jsonify({
            "code": 400,
            "data": {},
            "msg": str(e)
        }), 400
    except Exception as e:
        return jsonify({
            "code": 500,
            "data": {},
            "msg": f"v0.0.9回测失败: {str(e)}"
        }), 500
